package cn.doctor.assistant.pad.api.login;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;

import cn.doctor.assistant.pad.api.bean.AssResponse;
import cn.doctor.assistant.pad.api.AssistAPI;
import cn.doctor.assistant.pad.api.bean.ReqBean;
import cn.doctor.assistant.pad.base.AssJsonRequest;
import cn.doctor.assistant.pad.base.ResultCallback;
import cn.doctor.assistant.pad.entity.AssUser;


/**
 * Created by jiaolf on 2016/3/23.
 */
public class LoginApi {
    public static final String METHOD_LOGIN = "login";

    public static void login(String username, String pwd, final ResultCallback<LoginResponse> callback) {
        // 封装请求参数
        LoginRequest request = new LoginRequest();
        request.setUsername(username);
        request.setPassword(pwd);
        // 构建请求对象
        ReqBean reqBean = new ReqBean();
        reqBean.setParams(request);
        reqBean.setMethod(METHOD_LOGIN);

        // 生成json String
        String jsonStrParams = JSON.toJSONString(reqBean);

        // 构建JsonRequest
        AssJsonRequest jsonRequest = new AssJsonRequest(jsonStrParams,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        AssResponse resp = JSON.parseObject(response, AssResponse.class);
                        Log.d("jzsn", response);
                        if (resp.isSuccess()) {
                            LoginResponse loginResponse = new LoginResponse();
                            AssistAPI.sessionID = resp.getJsonValue("sid");
                            loginResponse.setSid(AssistAPI.sessionID);
                            loginResponse.setAssitant(JSON.parseObject(resp.getJsonValue("assitant"), AssUser.class));
                            loginResponse.setDoctor_array(JSON.parseArray(resp.getJsonValue("doctor_array"), AssUser.class));
                            callback.onSuccess(loginResponse);
                        } else {
                            callback.onFail("登录失败：" + resp.getResult().getInfo());
                        }
                    }
                });

        jsonRequest.setTag(METHOD_LOGIN);
        AssistAPI.getRequestQueue().add(jsonRequest);
    }
}
